package com.zxjbyte.yiyi.extension.job.core.listener;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.Matcher;
import org.quartz.impl.matchers.EverythingMatcher;
import org.quartz.listeners.JobListenerSupport;

import java.util.Objects;

/**
 * 默认全局Job监听器
 *
 * Job监听器用于监听Job的执行事件
 *
 * @Author zhangxingjia
 * @Date 2023/11/2 19:51
 * @Version: 1.0
 */
public class DefaultGlobalJobListener extends JobListenerSupport {

    private final String name;

    public DefaultGlobalJobListener(String name){
        this.name = name;
    }

    public DefaultGlobalJobListener(){
        this("myDefaultGlobalJobListener");
    }

    /**
     * 获取全部Job匹配
     * @return
     */
    public Matcher<JobKey> getMatcher() {
        return EverythingMatcher.allJobs();
    }

    /**
     * job监听器名称
     * @return
     */
    @Override
    public String getName() {
        return name;
    }

    /**
     * 在Job将要被执行时调用
     * @param context
     */
    @Override
    public void jobToBeExecuted(JobExecutionContext context) {
        getLog().info("Job is about to be executed >>> jobKey: {}", context.getJobDetail().getKey());
    }

    /**
     * 在Job将要被执行时，但被触发器的否决（veto）之后调用。
     * @param context
     */
    @Override
    public void jobExecutionVetoed(JobExecutionContext context) {
        getLog().info("Job execution was vetoed >>> jobKey: {}", context.getJobDetail().getKey());
    }

    /**
     * 在Job被执行之后调用。
     * @param context
     * @param jobException
     */
    @Override
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
        getLog().info("Job was executed >>> jobKey: {}", context.getJobDetail().getKey());
        if(Objects.nonNull(jobException)){
            getLog().error("Job execution exception: {}", jobException.getMessage());
            jobException.printStackTrace(); // 这里打印异常堆栈信息
        }
    }
}
